<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- to 写路径 跳转到指定路径 -->
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 自带阴影,立体效果,背景白色 -->
    <el-card class="box-card">
      <!--el-form  inline可以让表单变成一行  -->
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input size="small" class="search" v-model="search" placeholder="请输入查询的用户名">
            <el-button slot="append" icon="el-icon-search" @click="query"></el-button>
          </el-input>
        </el-form-item>
        <!-- 后边的按钮 -->
        <el-form-item class="add">
          <el-button type="primary" size="small" @click="centerDialogVisible = true">添加用户</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 stripe是否显示斑马 data数组,展示的数据,border 是否有边框  -->
      <el-table stripe :data="userData" border>
        <!-- width 某一列的宽,label 表格头的名字  prop 里边数对象的属性名 type="index" 是否使用序列号  -->
        <el-table-column type="index" label="序号" width="80">
        </el-table-column>

        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>

        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>

        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>

        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>

        <el-table-column label="状态" width="80">
          <!-- 作用域插槽  -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" >
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="getUseById(scope.row.id)"></el-button>
            <!--top 上 buttom下  left左 right右 start end  content 提示信息 -->
            <el-tooltip class="item" effect="light" content="删除角色" placement="top-start">
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="delUseById(scope.row.id)"></el-button>
            </el-tooltip>

            <!-- el-tooltip鼠标悬浮 给提示 effect 显示的背景颜色 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="distributeRole(scope.row)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 page-sizes 每页显示的数据数 page-size 控制的是默认显示数据条数   total 数据的总条数,总共的页数,算出来的 layout 控制组件的显示 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[1, 3, 5, 10]"
        :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="userData.length != 0 ? total : 0">
      </el-pagination>

    </el-card>
    <!-- title 标题信息 visible 控制对话框是否显示的 width 设置宽度, center 是否居中 -->
    <el-dialog title="添加用户" :visible.sync="centerDialogVisible" width="50%" @closed="resetUser">

      <!-- 表单 默认的插槽 label-position 对齐方式  -->
      <el-form ref="userformRef" :model="userform" label-position="right" :rules="ruleform">
        <!-- prop 使用rules对象的哪个校验规则 -->
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input v-model="userform.username" autofocus autocomplete="off" placeholder="输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="100px" prop="password">
          <el-input v-model="userform.password" autocomplete="off" placeholder="输入密码"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="100px" prop="email">
          <el-input type="email" v-model="userform.email" autocomplete="off" placeholder="输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="100px" prop="mobile">
          <el-input type="tel" v-model="userform.mobile" autocomplete="off" placeholder="输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- title 标题信息 visible 控制对话框是否显示的 width 设置宽度, center 是否居中 -->
    <el-dialog title="修改信息" :visible.sync="centerDialogVisibleUpdate" width="50%" @closed="resetUser">
      <!-- 表单 默认的插槽 label-position 对齐方式  -->
      <el-form ref="userUpdataformRef" :model="userform" label-position="right" :rules="ruleform">
        <!-- prop 使用rules对象的哪个校验规则 -->
        <el-form-item label="用户名" label-width="100px" prop="username">
          <el-input disabled v-model="userform.username" autocomplete="off" placeholder="输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="100px" prop="email">
          <el-input type="email" v-model="userform.email" autocomplete="off" placeholder="输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="100px" prop="mobile">
          <el-input type="tel" v-model="userform.mobile" autocomplete="off" placeholder="输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisibleUpdate = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="centerDialogVisibleRole" width="50%" @closed="resetUser">
      <el-row>
        <el-col :span="3" class="col-right"> 当前用户: </el-col>
        <el-col :span="21"> {{ userRow.username }} </el-col>
      </el-row>

      <el-row>
        <el-col :span="3" class="col-right"> 当前角色: </el-col>
        <el-col :span="20"> {{ userRow.role_name }} </el-col>
      </el-row>

      <el-row>
        <el-col :span="3" class="col-right"> 分配角色: </el-col>
        <el-col :span="20">
          <el-select v-model="role_id" placeholder="选择角色">
            <el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <!-- 具名插槽 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisibleRole = false">取 消</el-button>
        <el-button type="primary" @click="usersIdRole">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
// 导入request 封住了axios
import request from '@/utils/request';
export default {
  data () {
    return {
      // 搜索框
      search: "",
      // 列表数据
      userData: [],
      // 当前页
      currentPage: "1",
      // 每页查询条数
      pageSize: 3,
      // 总共条数
      total: 0,
      // 控制对话框显示
      centerDialogVisible: false,
      // 需要重新的回复数据
      userform: {
        username: '',
        password: "",
        email: "",
        mobile: ""
      },
      centerDialogVisibleUpdate: false,
      // 控制住更新的对话框显示
      // centerDialogVisible: false,
      // 里边写校验规则
      ruleform: {
        username: [
          // required必填项,不能是空 message 错误信息 trigger 触发条件
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          // 123@qq.com
          // sdfs@qq.com
          // sdfs_sdf@qq.com.cn
          { pattern: /^\w+(?:\.[_a-zA-Z0-9-]+)*@\w*qq.com$/, message: '请输入qq邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[34578]\d{9}/, message: '请输入正确手机号', trigger: 'blur' }
        ]
      },
      // 分配角色
      // 控制的是分配角色的对话框显示
      centerDialogVisibleRole: false,
      // 保存table 一行数据
      userRow: {},
      // 角色id
      role_id: "",
      // 所有的角色信息
      roleList: []
    }
  },
  // 生命周期
  mounted () {
    this.getUser()
  },
  methods: {

    query () {
      // 每次搜索,页数从1开始
      this.currentPage = 1
      this.getUser()
    },
    // 遍历用户信息
    async getUser () {
      const { data: { data, meta } } = await request({
        // 拿到公共的数据,改变后的
        url: `/users?query=${this.search}&pagenum=${this.currentPage}&pagesize=${this.pageSize}`,
        method: "GET"
      })
      if (meta.status !== 200) {
        // this.$message.error(meta.msg)
        this.$message.error("获取数据失败")
        return;
      }
      // 通过meta,是失败还是成功
      // back.then((data) => {
      //   console.log(data);
      // })
      // console.log('------', data, meta);
      // pagenum total users
      this.$data.userData = data.users
      this.$data.total = data.total
      this.$message.success("获取成功")
    },
    // // 上一页,改变后的页面
    // handlePrevClick (val) {
    //   console.log(`上一页 ${val} 条`);
    // },
    // // 下一页,会传来改变后的页数
    // handleNextClick (val) {
    //   console.log(`下一页: ${val}`);
    // },
    // 会传值,改变后的页面条数
    handleSizeChange (val) {
      this.$data.pageSize = val
      this.getUser()
    },
    // 点击页面,会传来改变后的页数
    async handleCurrentChange (val) {
      this.$data.currentPage = val
      this.getUser()
    },
    // 添加用户
    addUser () {
      // this.$refs.userformRef
      // 会将所有的input表单校验
      // this.$refs['userformRef'].validate(async (valid) => {
      this.$refs.userformRef.validate(async (valid) => {
        // 如果是false
        if (!valid) {
          return this.$message.error("请填写正确信息")
        }
        const { data: { meta } } = await request({
          url: "/users",
          method: "POST",
          // type
          data: this.userform
        })
        // console.log(meta);
        if (meta.status !== 201) {
          if (meta.status !== 400) {
            return this.$message.error("网络异常,稍后重试")
          }
          return this.$message.error(meta.msg)
        }
        this.$message.success(meta.msg)
        this.centerDialogVisible = false
        // 添加成功之后刷新
        this.getUser()
      });
      // console.log(back);
    },
    // 将数据重置
    resetUser () {
      // 数据重置
      // 初始化时候的数据
      // console.log(this.$options.data().userform);
      // this.userform = this.$options.data().userform
      Object.assign(this.userform, this.$options.data().userform)
    },
    // 根据id获取到用户信息
    async getUseById (id) {
      // console.log(id);
      // id = 500
      // {}配置对象
      const { data: { data, meta } } = await request({
        url: `/users/${id}`,
        method: "GET"
      })
      // console.log(data, meta);
      // 获取数据失败
      if (meta.status !== 200) {
        return this.$message.error("网络异常,稍后重试")
      }
      // 成功,将后台的数据,付给userform,将id附上了
      Object.assign(this.userform, data)
      // console.log(this.userform);
      // 显示对话框
      this.centerDialogVisibleUpdate = true
    },
    // 更新用户
    updateUser () {
      this.$refs.userUpdataformRef.validate(async (valid) => {
        // console.log(valid);
        // 校验没哟通过
        if (!valid) {
          return this.$message.error("填写正确数据")
        }
        // 使用包装过的axios,request
        const { data: { meta } } = await request({
          // 少id
          url: `/users/${this.userform.id}`,
          method: "PUT",
          data: this.userform
        })
        // 获取数据失败
        if (meta.status !== 200) {
          return this.$message.error("网络异常,稍后重试")
        }
        // 先关闭,在便利
        this.centerDialogVisibleUpdate = false
        // 重新便利
        this.getUser()
      })
    },
    // 根据id 删除
    async delUseById (id) {
      try {
        await this.$confirm('是否删除数据?', '危险', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'error'
        })
        const { data: { meta } } = await request({
          url: `/users/${id}`,
          method: "DELETE"
        })
        // console.log(data, meta);
        // 获取数据失败
        if (meta.status !== 200) {
          return this.$message.error("网络异常,稍后重试")
        }
        // 页数> 1 并数据只有1条 跳转到上一页
        if (this.currentPage > 1 && this.userData.length === 1) {
          this.currentPage = this.currentPage - 1
        }
        // 刷新数据
        this.getUser()
        return this.$message.success(meta.msg)
      } catch (error) {
        // console.log("error---->", error);
        return this.$message.info("已经取消")
      }
    },
    // 分配角色
    async distributeRole (user) {
      console.log(user);
      // 显示分配角色对话框
      this.centerDialogVisibleRole = true
      this.userRow = user;
      // 获取到所有的角色
      const { data: { data, meta } } = await request({
        url: "/roles",
        method: "GET"
      })
      console.log(meta);
      if (meta.status !== 200) {
        return this.$message.error("网络异常,稍后重试")
      }
      this.roleList = data
    },
    // 更新用户的角色
    async usersIdRole () {
      const { data: { data, meta } } = await request({
        url: `users/${this.userRow.id}/role`,
        data: { rid: this.role_id },
        method: "PUT"
      })
      console.log(data, meta);
      if (meta.status !== 200) {
        return this.$message.error("网络异常,稍后重试")
      }
      // 关闭对话框
      this.centerDialogVisibleRole = false
      // 重新给role_id 赋值
      this.role_id = "";
      // 重新便利用户信息
      this.getUser()
    }
  }
}
</script>

<style scoped lang="less">
.el-card {
  margin-top: 20px;
}

.search {
  width: 540px;
}

.col-right {
  text-align: right;
  padding-right: 10px;
}

.el-row {
  margin-top: 10px;
}
</style>
